import $H from './request.js';
import $C from './config.js';
import $store from '@/store/index.js'
export default {
	setStore(name, val) {
		var obj = {
			name: name,
			value: val
		}
		$store.commit('setState', obj);
	},
	init_jingmo_login() { // 微信公众号 静默登录
		// #ifdef H5
		let ua = navigator.userAgent.toLowerCase();
		if (uni.getStorageSync('token') || ua.match(/MicroMessenger/i) != "micromessenger") {
			return
		}
		let link = window.location.href;
		if (link.indexOf("?code") != -1) {
			return
		}
		this.login_init({}).then(ret => {
			this.settings = ret.settings;
			this.plugin_set = ret.plugin_set;
			let link = window.location.href;
			if (link.indexOf("?code") != -1) {
				link = uni.getStorageSync('link')
			} else {

				this.setStorage('link', link);
			}
			let code = null;
			if (!this.settings) {
				return;
			}
			let appid = this.settings['apppid'];
			var http = window.location.protocol;
			var com = window.location.host;
			var url = encodeURIComponent(link);
			const protocol = window.location.protocol;
			const host = window.location.host;
			url = protocol + host
			url = encodeURIComponent(link);
			var wx = 'https://open.weixin.qq.com/connect/oauth2/authorize';
			var wx_code = '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
			window.location.href = wx + `?appid=${appid}&redirect_uri=${url}` + wx_code;

		})
		// #endif
	},
	is_login() {
		if (!uni.getStorageSync('token')) {
			uni.navigateTo({
				url: '/pages/banmi/user_login'
			})
			return false
		}
		return true
	},
	mp_baidu_login(data) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/Baidulogin/Login', data).then(ret => {
				this.success(ret.msg);
				if (ret.status == 401) {
					return
				}

				if (ret.status == 200 || ret.status == 201) {
					this.login_ok(ret.data.user, ret, res);
				}
			})

		});
	},
	app_Apple_login(data) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/Applelogin/Login', data).then(ret => {
				this.success(ret.msg);

				if (ret.status == 200 || ret.status == 201) {
					this.login_ok(ret.data.user, ret, res);
				}
			})

		});
	},
	mp_kuai_login(data) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/Kuaishoulogin/Login', data).then(ret => {
				this.success(ret.msg);
				uni.hideLoading()
				if (ret.status == 401) {
					return
				}

				if (ret.status == 200 || ret.status == 201) {
					this.login_ok(ret.data.user, ret, res);
				}


			})

		});
	},
	app_wx_login(data) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/Wxlogin/app_wx_login', data).then(ret => {
				console.log("ret: " + JSON.stringify(ret));
				this.success(ret.msg);
				if (ret.status == 200 || ret.status == 201) {
					this.login_ok(ret.data.user, ret, res);
				}
			})

		});
	},
	app_version(data) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/app/version', data).then(ret => {
				res(ret)
			})

		});
	},
	user_reg(data) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/reg/AccountReg', data).then(ret => {

				this.success(ret.msg);

				if (ret.status == 200 || ret.status == 201) {
					this.login_ok(ret.data.user, ret, res);
				}
			})

		});
	},
	mp_wx_login_tel(data) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/Wxlogin/mp_wx_login_tel', data).then(ret => {
				this.success(ret.msg);
				if (ret.status == 200 || ret.status == 201) {
					this.login_ok(ret.data.user, ret, res);
				}
			})

		});
	},
	getPhoneNumber(data) {
		return new Promise((res, rej) => {
			if (!data.agr) {

				this.success('请勾选同意协议');
				return;
			}
			if (data.errMsg == 'getPhoneNumber:fail user deny') {

				this.success('请同意微信手机号授权');
				return;
			}
			wx.checkSession({
				success() {
					data.encryptedData
					res(data.wx_code);
				},
				fail() {
					wx.login({
						success(res) {
							if (res.code) {
								res(res.wx_code);
							}
						}
					})
				}
			})
		});
	},
	mp_wx_code() {
		return new Promise((res, rej) => {
			wx.login({
				success(ret) {
					if (ret.code) {
						res(ret.code);
					}
				}
			})
		});
	},
	get_imgCode(data) {
		return new Promise((res, rej) => {
			let RandomSixStr = ''
			for (let i = 0; i < 10; i++) {
				RandomSixStr += String(Math.floor(Math.random() * 10))
			}
			data.code_img_rand = data.code_img + '?id=' + RandomSixStr;
			data.v_id = RandomSixStr;
			res(data);

		});
	},
	tel_message(data) {
		return new Promise((res, rej) => {
			if (!data.agr && data.is_agr) {

				this.success('请勾选同意协议');
				return;
			}
			if (!data.phone) {
				this.success('请输入手机号');

				return;
			}

			$H.post('/banmi.php/Sms/TelMessage', data).then(ret => {

					this.success(ret.msg);
					if (ret.status == 200) {
						res(200);
					}
				}

			)
		});
	},
	login_init(data) {
		let RandomSixStr = ''
		for (let i = 0; i < 10; i++) {
			RandomSixStr += String(Math.floor(Math.random() * 10))
		}
		let requestParams = {
			id: RandomSixStr
		};
		return new Promise((res, rej) => {
			$H.post('/banmi.php/login/LoginInit', requestParams).then(ret => {

				requestParams.find = ret.data.find;
				requestParams.plugin_set = ret.data.plugin_set;
				requestParams.settings = ret.data.settings;
				requestParams.settings.reg_img_code = ret.reg_img_code;
				requestParams.settings.code_img_rand = ret.data.settings.code_img + '?id=' +
					RandomSixStr;
				requestParams.settings.code_img = ret.data.settings.code_img;
				requestParams.settings.v_id = RandomSixStr;

				res(requestParams);
			})
		});
	},
	mp_wx_login(requestParams) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/wxlogin/mp_wx_login', requestParams).then(ret => {
				uni.hideLoading()
				if (ret.status == 200 || ret.status == 201) {
					this.login_ok(ret.data.user, ret, res);
					return
				}

				res(ret.status);
				// uni.showToast({
				// 	title: ret.msg,
				// 	icon: 'none',
				// 	duration: 4000
				// });
				this.success(ret.msg);
			})
		});
	},
	ali_login(requestParams) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/Alilogin/Login', requestParams).then(ret => {
				uni.hideLoading()
				if (ret.status == 401) {
					this.success(ret.msg);
					return
				}
				if (ret.status == 200 || ret.status == 201) {
					this.login_ok(ret.data.user, ret, res);
				} else {
					res(ret.data)
				}
			})
		});
	},
	qq_login(requestParams) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/Qqlogin/Login', requestParams).then(ret => {
				uni.hideLoading()


				if (ret.status == 401 || ret.status == 402) {
					this.success(ret.msg);
					return
				}
				if (ret.status == 200 || ret.status == 201) {
					this.login_ok(ret.data.user, ret, res);
				} else {
					res(ret.data)
				}
			})
		});
	},
	douyin_login(requestParams) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/Doulogin/Login', requestParams).then(ret => {
				uni.hideLoading()
				if (ret.status == 401 || ret.status == 0) {
					this.success(ret.msg);
					return
				}
				if (ret.status == 200 || ret.status == 201) {

					this.login_ok(ret.data.user, ret, res);
				} else {
					res(ret.data)
				}
			})
		});
	},
	//微信公众号登录
	h5_jingmo_weixin_login() {
		let link = window.location.href;
		let code = null;
		let temp = link.split("code=")[1];
		if (!temp) {
			return
		}
		code = temp.split("&")[0];
		if (code == uni.getStorageSync('h5_wx_code')) {
			return
		}



		uni.navigateTo({
			url: '/pages/banmi/user_login'
		})

		// uni.setStorage({
		// 	key: 'h5_wx_code',
		// 	data: code
		// });
		// let requestParams = {
		// 	code: code,
		// 	id: this.v_id,
		// 	is_login: '静默登录'
		// };
		// this.h5_weixin_login(requestParams).then(ret => {
		// 	if (ret == 40163) {
		// 		return
		// 	}

		// })
	},
	h5_weixin_login(requestParams) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/Wxlogin/h5_weixin_login', requestParams).then(ret => {
				//公众号
				if (requestParams.is_login == '静默登录') {
					var data = ret.data;
					var user = ret.data.user
					if (data.force_tel == 1 && user.tel == '') {
						// this.error('请完善资料');
						user['code'] = 100;
						return
					}

					if (data.force_face == 1) {
						if (user.face == '' || user.nickname == '') {
							this.error('请完善资料');
							user['force_face'] = data.force_face;
							user['code'] = 100;
							res(user);
							return
						}
					}

					this.setStorage('token', user.token);
					this.setStorage('uid', user.uid);
					this.setStorage('user', user);

					uni.$emit('banmi_login', {
						title: 1,
					});
					return
				}
				uni.showToast({
					title: ret.msg,
					icon: 'none',
					duration: 4000
				});

				if (ret.status == 40163) {
					res(ret.status);
					return
				}
				if (ret.status == 200 || ret.status == 201) {
					this.login_ok(ret.data.user, ret, res);
				}

			})
		});
	},
	pwd_login(requestParams) {
		return new Promise((res, rej) => {
			$H.post('banmi.php/Reg/PwdLogin', requestParams).then(ret => {
				uni.showToast({
					title: ret.msg,
					icon: 'none',
					duration: 4000
				});
				if (ret.status == 200) {
					this.login_ok(ret.data.user, ret, res);
				}
			})
		});
	},
	app_tel_login(requestParams) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/reg/SmsTelLogin', requestParams).then(ret => {

				uni.showToast({
					title: ret.msg,
					icon: 'none',
					duration: 4000
				});
				if (ret.status == 200 || ret.status == 201) {
					this.login_ok(ret.data.user, ret, res);
				}
			})
		})
	},
	error(title) {
		uni.showToast({
			title: title,
			icon: 'error'
		})
	},
	success(title) {
		uni.showToast({
			title: title,
			icon: 'none',
			duration: 3000
		})
	},
	login_ok(user, data, res) {
		user.force_tel = data.force_tel;
		user.force_face = data.force_face;
		user.img_url = data.img_url;
		var msg = '';
		if (data.force_tel == 1 && user.tel == '') {
			this.error('请完善资料');
			user['code'] = 100;
			res(user);
			return
		}

		if (data.force_face == 1) {
			if (user.face == '' || user.nickname == '') {
				this.error('请完善资料');
				user['force_face'] = data.force_face;
				user['code'] = 100;
				res(user);
				return
			}
		}

		// this.success(data.msg);
		uni.hideLoading()
		uni.showLoading({
			title: data.msg,
			mask: true
		})


		this.setStorage('token', user.banmi_token);
		this.setStorage('uid', user.uid);
		this.setStorage('user', user);

		setTimeout(function() {
			uni.$emit('banmi_login', {
				title: 1,
			});
			uni.hideLoading()
			uni.switchTab({
				url: '/' + $C.jump_index
			})
		}, 2000);
	},
	User_pwa_tel(requestParams) {
		return new Promise((res, rej) => {
			var url = '/banmi.php/reg/PwdBindTel';
			$H.post(url, requestParams).then(ret => {
				this.success(ret.msg);
				if (ret.status == 200 || ret.status == 201) {
					this.login_ok(ret.data.user, ret, res);
				}
			})
		});
	},
	//分销
	inviteview() {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/Invite/inviteview', {}).then(ret => {
				if (ret.status == 200) {
					var face = ret.data.user.face;
					if (!face) {
						ret.data.user.face = $C.baseUrl + '/attachment/face/face.png'
					} else {
						var is_face = face.indexOf("https") != -1;
						if (!is_face) {
							ret.data.user.face = ret.img_url + face;
						}
					}

					res(ret.data);
				}
			})
		});
	},
	//个人基本信息
	user_info() {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/User/index').then(ret => {

				if (ret.status == 200) {
					if (!ret.data.user) {
						uni.removeStorageSync('user_id');
						uni.removeStorageSync('token');
						uni.removeStorageSync('user');
						res(0);
						return
					}
					var face = ret.data.user.face;
					ret.data.user.face1 = ret.data.user.face;
					ret.data.user.force_tel = ret.data.force_tel
					ret.data.user.force_face = ret.data.force_face
					uni.setStorage({
						key: 'user',
						data: ret.data.user
					});
					res(ret);
				} else {
					uni.removeStorageSync('user_id');
					uni.removeStorageSync('token');
					uni.removeStorageSync('user');
					res(0);
				}
			})
		});
	},
	edit_account(val) {
		return new Promise((res, rej) => {
			let requestParams = {
				account: val
			};
			$H.post('/banmi.php/User/EditAccount', requestParams).then(ret => {

				this.success(ret.msg);
				if (ret.status == 200) {
					res(200);
				} else {
					res(0);
				}
			})
		});
	},
	edit_nickname(requestParams) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/User/EditNickname', requestParams).then(ret => {
				this.success(ret.msg);
				if (ret.status == 200) {
					if (uni.getStorageSync('token')) {
						uni.$emit('banmi_nickname', {
							nickname: requestParams.nickname,
						});
					}

					res(200);
				} else {
					res(0);
				}
			})
		});
	},
	edit_face(requestParams) {
		return new Promise((res, rej) => {
			$H.post('/banmi.php/User/EditFace', requestParams).then(ret => {
				this.success(ret.msg);
				if (ret.status == 200) {
					uni.$emit('banmi_face', {
						face: requestParams.face,
					});
					res(ret.img_url + requestParams.face);
				} else {
					res(0);
				}
			})
		});
	},
	edit_Gender(val) {
		return new Promise((res, rej) => {
			let requestParams = {
				gender: val
			};
			$H.post('/banmi.php/User/EditGender', requestParams).then(ret => {
				this.success(ret.msg);
				if (ret.status == 200) {
					res(200);
				} else {
					res(0);
				}
			})
		});
	},
	User_out() {
		return new Promise((res, rej) => {
			let requestParams = {
				gender: 0
			};
			$H.post('/banmi.php/User/UserOut', requestParams).then(ret => {
				if (ret.status == 200) {
					res(ret.data);
				} else {
					res(0);
				}
			})
		});
	},
	//绑定手机号
	User_app_account_tel(requestParams) {
		return new Promise((res, rej) => {
			var url = '/banmi.php/bind/AppAccountTel';
			if (requestParams.encryptedData) {
				var url = '/banmi.php/bind/MpWxBindTel';
			}
			$H.post(url, requestParams).then(ret => {
				this.success(ret.msg);
				res(ret);
			})
		});
	},
	app_updata(is) {
		//#ifdef APP
		return new Promise((res, rej) => {
			// app更新 
			plus.runtime.getProperty(plus.runtime.appid, (inf) => {
				//获取服务器的版本号 
				let requestParams = {
					edition_type: plus.runtime.appid,
					version_type: uni.getSystemInfoSync().platform, //android或者ios
					edition_number: inf.versionCode, // 打包时manifest设置的版本号 
					edition_version: inf.version
				};

				$H.post('/banmi.php/app/AppUpdata', {}).then(ret => {


					if (is == 1) {
						res(ret);
						return;
					}

					if (ret.status == 200) {

						var data = ret.data;
						if (data.up_code == 9001) {
							//调用静默更新方法 传入下载地址 
							silenceUpdate(data.edition_url, data.edition_silence)
						} else if (data.up_code == 9000) {
							//提示下载更新
							setTimeout(() => {
								uni.navigateTo({
									url: '/uni_modules/rt-uni-update/rt-uni-update?obj=' +
										JSON.stringify(data)
								});
							}, 500)

						}

					}
				})
			});
		});
		//#endif  
	},
	appinit_h5() {
		// #ifdef H5
		var url = window.location.href;
		var data = window.location.protocol + '//' + window.location.host;

		function isPureNumber(str) {
			return /^\d+$/.test(str);
		}
		data = url.replace(data, "")
		let arr = data.split("/");

		for (var i = 0; i < arr.length; i++) {
			var is = isPureNumber(arr[i]);
			if (is) {
				var saas_id = arr[i];
				uni.setStorageSync('saas_id', saas_id);

			}
		}
		var locationhref = window.location.href;
		let a = locationhref.indexOf("#/")
		var home_url = locationhref.substring(0, a)

		// #endif
	},
	//初始化
	appinit() {
		let platform = '';
		// #ifdef MP-WEIXIN
		platform = 'MP-WEIXIN';
		// #endif 
		// #ifdef APP
		platform = uni.getSystemInfoSync().platform;
		if (platform === 'ios') {
			platform = 'Ios-App';
		} else {
			platform = 'Android-App';
		}
		// #endif
		// #ifdef MP-TOUTIAO
		platform = 'MP-TOUTIAO';
		// #endif
		// #ifdef MP-ALIPAY
		platform = 'MP-ALIPAY';
		// #endif
		// #ifdef MP-BAIDU
		platform = 'MP-BAIDU';
		// #endif
		// #ifdef MP-360
		platform = 'MP-360';
		// #endif
		// #ifdef MP-JD
		platform = 'MP-JD';
		// #endif
		// #ifdef MP-KUAISHOU
		platform = 'MP-KUAISHOU';
		// #endif
		// #ifdef MP-QQ
		platform = 'MP-QQ';
		// #endif
		// #ifdef H5 
		//判断是否是微信公众号
		let ua = navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i) == "micromessenger") {
			platform = 'mp-weixin';
		} else {
			platform = 'H5';
		}

		if (!uni.getStorageSync('token')) {
			this.h5_jingmo_weixin_login();
		}
		// #endif
		this.setStorage('platform', platform);
		uni.getSystemInfo({
			success: (res) => {
				this.setStorage('system', res.system);
				this.setStorage('uniPlatform', res.uniPlatform);
				this.setStorage('model', res.model);
				this.setStorage('browserName', res.browserName);
				this.setStorage('screenHeight', res.screenHeight);
				this.setStorage('deviceBrand', res.deviceBrand);
				this.setStorage('brand', res.brand);
				this.setStorage('appVersion', res.appVersion);
				this.setStorage('deviceModel', res.deviceModel);
				this.setStorage('model', res.model);
				this.setStorage('osAndroidAPILevel', res.osAndroidAPILevel);
				this.setStorage('romName', res.romName);
				this.setStorage('romVersion', res.romVersion);
				this.setStorage('system', res.system);
			}
		})

	},
	setStorage(key, data) {

		uni.setStorage({
			key: key,
			data: data
		});
	}

}